package com.flydust.apipulse.service;

import com.qiniu.storage.UploadManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
import java.util.logging.Logger;
import java.util.logging.Level;

@Service
public class QiniuFileUploadService {

    private static final Logger logger = Logger.getLogger(QiniuFileUploadService.class.getName());

    @Autowired
    private Auth auth;

    @Autowired
    private com.qiniu.storage.Configuration qiniuConfiguration;

    @Value("${qiniu.bucketName}")
    private String bucketName;

    @Value("${qiniu.domain}")
    private String domain;

    /**
     * 上传文件到七牛云
     * @param file 文件
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    public String uploadFile(MultipartFile file) throws IOException {
        logger.info("开始上传文件到七牛云，文件名: " + file.getOriginalFilename() + ", 大小: " + file.getSize());
        
        try {
            // 构造一个带指定Zone对象的配置类
            UploadManager uploadManager = new UploadManager(qiniuConfiguration);

            // 生成上传凭证
            String upToken = auth.uploadToken(bucketName);
            logger.fine("生成上传凭证: " + upToken);

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String key = UUID.randomUUID().toString() + fileExtension;
            logger.fine("生成文件名: " + key);

            // 上传文件
            uploadManager.put(file.getBytes(), key, upToken);
            logger.info("文件上传成功");

            // 返回文件访问地址
            String fileUrl = domain + "/" + key;
            logger.info("文件访问URL: " + fileUrl);
            return fileUrl;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "上传文件到七牛云失败", e);
            throw e;
        }
    }
}